package com.dd.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.reggie.common.CustomException;
import com.dd.reggie.dto.DishDto;
import com.dd.reggie.entity.Dish;
import com.dd.reggie.entity.DishFlavor;
import com.dd.reggie.entity.Setmeal;
import com.dd.reggie.mapper.DishMapper;
import com.dd.reggie.service.DishFlavorService;
import com.dd.reggie.service.DishService;
import com.dd.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService{

    @Autowired
    private DishFlavorService dishFlavorService;

    /**
     * 涉及到多个表的操作，应在service层进行，需要加入事务控制注解Transactional
     * 实现新增菜品信息，关联到两个表的操作
     *
     * @param dishDto
     */
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //首先保存dish的信息,才能生成dishId
        this.save(dishDto);

        //然后提炼出dishId，放在dishFlavor中
        //注意dishDto中的dishFlavor只有name与value
        Long id = dishDto.getId();
        List<DishFlavor> flavors = dishDto.getFlavors();

        for(DishFlavor flavor : flavors){
            flavor.setDishId(id);
        }

        dishFlavorService.saveBatch(flavors);
    }

    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查询所选菜品状态，均为停售状态才可删除,即下方count = ids.size()时
        //select count(*) form dish where id in (1,2,3,...) and status = 0
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId, ids).eq(Dish::getStatus, 0);
        int count = super.count(queryWrapper);

        //若不全为售卖状态则抛出异常
        if(count < ids.size()){
            throw new CustomException("菜品状态不全为停售，不可批量删除！");
        }

        //满足条件，删除套餐数据
        this.removeByIds(ids);

        //删除关联表（口味表）数据
        //delete form dish_flavor where dish_id in ids
        LambdaQueryWrapper<DishFlavor> queryWrapperFlavor = new LambdaQueryWrapper<>();
        queryWrapperFlavor.in(DishFlavor::getDishId, ids);
        dishFlavorService.remove(queryWrapperFlavor);
    }
}
